<?php
// +----------------------------------------------------------------------
// 公共函数文件
// +----------------------------------------------------------------------

// 获取客户端IP地址
function get_real_ip()
{
	$ip=false;
	if(!empty($_SERVER["HTTP_CLIENT_IP"])){
	  $ip = $_SERVER["HTTP_CLIENT_IP"];
	}
	if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
	  $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
	  if($ip){
	   array_unshift($ips, $ip); $ip = FALSE;
	  }
	  for($i = 0; $i < count($ips); $i++){
	   if (!eregi ("^(10|172\.16|192\.168)\.", $ips[$i])){
	    $ip = $ips[$i];
	    break;
	   }
	  }
	}
	return($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}

//二维数组去掉重复值
function array_to_arrone($arr)
{
    foreach ($arr as $k => $v) {
        foreach ($v as $m => $n) {
            $temp[] = $n;
        }
    }
    return $temp;
}

// 获取文章中的收张图片
function getpic($content){
	$data['content']=$content;//获取的内容  
	$soContent=$data['content'];  
	$soImages = '~<img [^>]* />~';  
	preg_match_all($soImages, $soContent, $thePics);
	if(empty($thePics[0])) return null;
	$allPics = count($thePics[0]);
	preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|PNG))\"?.+>/i',$thePics[0][0],$match);  
	$data['img']=$thePics[0][0];  
	//dump($data['img']);  
	if($allPics> 0){  
		return $match[1];  
	}else {  
		return null;  
	}  
}
  
// 功能：计算两个时间戳之间相差的日时分秒
// $begin_time  开始时间戳
// $end_time 结束时间戳
function timediff($begin_time,$end_time)
{
      if($begin_time < $end_time){
         $starttime = $begin_time;
         $endtime = $end_time;
      }else{
         $starttime = $end_time;
         $endtime = $begin_time;
      }

      //计算天数
      $timediff = $endtime-$starttime;
      $days = intval($timediff/86400);
      //计算小时数
      $remain = $timediff%86400;
      $hours = intval($remain/3600);
      //计算分钟数
      $remain = $remain%3600;
      $mins = intval($remain/60);
      //计算秒数
      $secs = $remain%60;
      $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
      return $res['day'];
}

/**
 * 三级分类查询
 * @return array 查询的结果
 */
function third_category($list,$fid)
{
    $arr = array();
    foreach ($list as $key => $value) {
        if ($value['pid'] == $fid) {
            $value['child'] = third_category($list,$value['id']);
            $arr[] = $value;
        }
        
    }
    return $arr;
}

/**
 * 删除目录及目录下所有文件或删除指定文件
 * @param str $path   待删除目录路径
 * @param int $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录（包含子目录）
 * @return bool 返回删除状态
 */
function delDirAndFile($path, $delDir = FALSE) {
    $handle = opendir($path);
    if ($handle) {
        while (false !== ( $item = readdir($handle) )) {
            if ($item != "." && $item != "..")
                is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
        }
        closedir($handle);
        if ($delDir)
            return rmdir($path);
    }else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return FALSE;
        }
    }
}

/**
 * 向百度推送文章
 */
function pushToBaidu($urls)
{
 $api = "http://data.zz.baidu.com/urls?site='www.yuqingyong.cn'&token=你的Token";
 $ch = curl_init();
 $options =  array(
   CURLOPT_URL => $api,
   CURLOPT_POST => true,
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_POSTFIELDS => implode("\n", $urls),
   CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
 );
 curl_setopt_array($ch, $options);
 $result = curl_exec($ch);
 return $result;
}

function bdUrls($urls) {
    $api = 'http://data.zz.baidu.com/urls?site=www.yuqingyong.cn&token=CPiBRFKrXgiEahWo';
    $ch = curl_init();
    $options =  array(
        CURLOPT_URL => $api,
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => implode("\n", $urls),
        CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
    );
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch);
    echo $result;
}

//参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
function curl_request($url,$post='',$cookie='', $returnCookie=0){
     $curl = curl_init();
     curl_setopt($curl, CURLOPT_URL, $url);
     curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
     curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
     curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
     curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
     if($post) {
         curl_setopt($curl, CURLOPT_POST, 1);
         curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
     }
     if($cookie) {
         curl_setopt($curl, CURLOPT_COOKIE, $cookie);
     }
     curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
     curl_setopt($curl, CURLOPT_TIMEOUT, 10);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     $data = curl_exec($curl);
     if (curl_errno($curl)) {
         return curl_error($curl);
     }
     curl_close($curl);
     if($returnCookie){
         list($header, $body) = explode("\r\n\r\n", $data, 2);
         preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
         $info['cookie']  = substr($matches[1][0], 1);
         $info['content'] = $body;
         return $info;
     }else{
         return $data;
     }
}


// 生成随机码
function getNoncestr($num=8)
{
    $arr = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0'];
    $tmpstr = '';
    $max = count($arr) - 1;
    for($i = 1;$i <= $num;$i++){
        $key = rand(1,$max);
        $tmpstr .= $arr[$key];
    }

    return $tmpstr;
}

// 判断是否是json格式的数据
function is_json($value) {
    $res = json_decode($value, true);
    $error = json_last_error();
    if (!empty($error)) {
      return false;
    }
    return true;
}

// 加密
function encode($str)
{
    if (mb_strlen($str) <= 1) return '';
    // 密锁串、长度、随机位及值
    $lock = 'tRL+CS1A967JBGMVem4Und5xac-_bzF0YNpWojk2vgIs8ThZ3=/EXOuHKrwPfiQDqly';
    $len = strlen($lock);
    $rand = mt_rand(0, $len - 1);
    $lk = $lock[$rand];
    // 密钥结合密锁随机值MD5加密
    $md5 = strtoupper(md5('0290ad5ed58b92959e2d567bf2648c5c' . $lk));
    // 字符串BASE64加密
    $str = base64_encode($str);
    $res = '';
    for ($i = $k = 0, $c = strlen($str); $i < $c; $i++) {
        $k === strlen($md5) && $k = 0;
        // 转化字符：由密锁串 原位+随机位+顺序MD5密钥字符ASCII码 决定新位，从密锁串中获取目标字符
        $res .= $lock[(strpos($lock, $str[$i]) + $rand + ord($md5[$k])) % ($len)];
        $k++;
    }
    // 返回加密结果(含随机关联)
    return $res . $lk;
}

// 解密
function decode($str)
{
    if (mb_strlen($str) <= 1) return '';
    // 将地址栏参数被强制转换的空格替换成+号
    $str = str_replace(' ', '+', $str);
    // 密锁串、长度、随机位及值
    $lock = 'tRL+CS1A967JBGMVem4Und5xac-_bzF0YNpWojk2vgIs8ThZ3=/EXOuHKrwPfiQDqly';
    $len = strlen($lock);
    // 字符串长度
    $txtLen = strlen($str);
    // 密锁随机值及位
    $lk = $str[$txtLen - 1];
    $rand = strpos($lock, $lk);
    // 密钥结合密锁随机值MD5加密
    $md5 = strtoupper(md5('0290ad5ed58b92959e2d567bf2648c5c' . $lk));
    // 去除字符串随机关联
    $str = substr($str, 0, $txtLen - 1);
    $tmpStream = '';
    for ($i = $k = 0, $c = strlen($str); $i < $c; $i++) {
        $k === strlen($md5) && $k = 0;
        // 获取字符在密锁串原位：由 位-随机位-顺序MD5密钥字符ASCII码 算出
        $j = strpos($lock, $str[$i]) - $rand - ord($md5[$k]);
        while ($j < 0) {
            $j += $len;
        }
        $tmpStream .= $lock[$j];
        $k++;
    }
    // 返回BASE64解密源字符串
    return base64_decode($tmpStream);
}

// 生成登录ID
function eLoginId($str)
{
    return encode(time() . '.' . chr(mt_rand(97, 122)) . '.' . $str);
}

// 登录ID解码
function dLoginId($loginId, $time = 7200)
{
    $_t = time();
    $arr = explode('.', decode($loginId));
    return count($arr) === 3 && is_numeric($t = $arr[0]) ? ($t <= $_t && $t + $time > $_t) ? $arr[2] : 0 : false;
}

// ----------------------------------------------------------------------
//  BASE64加解密
// ----------------------------------------------------------------------

function en64($str)
{
    return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($str));
}

function de64($str)
{
    return base64_decode(str_replace(['-', '_'], ['+', '/'], $str));
}


/**
 * [将Base64图片转换为本地图片并保存]
 * @E-mial wuliqiang_aa@163.com
 * @TIME   2017-04-07
 * @WEB    http://blog.iinu.com.cn
 * @param  [Base64] $base64_image_content [要保存的Base64]
 * @param  [目录] $path [要保存的路径]
 */
function base64_image_content($base64_image_content,$path){
    //匹配出图片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        $type = $result[2];
        $new_file = $path."/".date('Ymd',time())."/";
        if(!file_exists($new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700);
        }
        $new_file = $new_file.time().getNoncestr(5).".{$type}";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            return '/'.$new_file;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/**
 * JSON返回
 *
 * param err_code 返回的错误编码
 * param err_msg  返回的错误信息
 * param err_dom  返回的DOM标识
 */
function json_return($err_code,$err_msg='',$err_dom='',$other_data=array()){
	$json_arr['err_code'] = $err_code;
	if($err_msg) $json_arr['err_msg'] = $err_msg;
	if($err_dom) $json_arr['err_dom'] = $err_dom;
	if(!empty($other_data)){
		$json_arr = array_merge($json_arr, $other_data);
	}
	if(!headers_sent()) header('Content-type:application/json');
	exit(json_encode($json_arr));
}


